﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

using System.IO;
using System.Data;

using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.POIFS;
using NPOI.Util;

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;



namespace KSOAPlus
{
    public class ExcelHelper
    {
        Common Init = new Common();
        /// <summary>
        /// 根据Excel和Sheet返回DataTable
        /// </summary>
        /// <param name="filePath">Excel文件地址</param>
        /// <param name="sheetIndex">Sheet索引</param>
        /// <returns>DataTable</returns>
        public DataTable GetDataTable(string filePath, int sheetIndex)
        {
            return GetDataSet(filePath, sheetIndex).Tables[0];
        }

        /// <summary>
        /// 根据Excel返回DataSet
        /// </summary>
        /// <param name="filePath">Excel文件地址</param>
        /// <param name="sheetIndex">Sheet索引，可选，默认返回所有Sheet</param>
        /// <returns>DataSet</returns>
        public DataSet GetDataSet(string filePath, int? sheetIndex = null)
        {
            DataSet ds = new DataSet();
            IWorkbook fileWorkbook;
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                if (Path.GetExtension(filePath) == ".xls")
                {
                    try
                    {
                        fileWorkbook = new HSSFWorkbook(fs);
                    }
                    catch (Exception ex)
                    {
                        Init.WriteLog(ex.ToString(), true);
                        throw ex;
                    }
                }
                else
                {
                    try
                    {
                        fileWorkbook = new XSSFWorkbook(fs);
                    }
                    catch(Exception ex)
                    {
                        Init.WriteLog(ex.ToString(), true);
                        fileWorkbook = new HSSFWorkbook(fs);
                    }
                }
            }

            for (int i = 0; i < fileWorkbook.NumberOfSheets; i++)
            {
                if (sheetIndex != null && sheetIndex != i)
                    continue;
                DataTable dt = new DataTable();
                ISheet sheet = fileWorkbook.GetSheetAt(i);

                //表头
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int j = 0; j < header.LastCellNum; j++)
                {
                    object obj = GetValueTypeForXLS(header.GetCell(j) as HSSFCell);
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + j.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(j);
                }
                //数据
                IEnumerator rows = sheet.GetEnumerator();
                while (rows.MoveNext())
                {
                    int j = sheet.FirstRowNum + 1;
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int K in columns)
                    {
                        dr[K] = GetValueTypeForXLS(sheet.GetRow(K).GetCell(K) as HSSFCell);
                        if (dr[K] != null && dr[K].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                    j++;
                }
                ds.Tables.Add(dt);
            }

            return ds;
        }

        /// <summary>
        /// 根据DataTable导出Excel
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="file">保存地址</param>
        public bool GetExcelByDataTable(DataTable dt, string file)
        {
            bool flag = false;
            try
            {
                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                GetExcelByDataSet(ds, file);
                flag = true;
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
                flag = false;
                
            }
            return flag;
        }

        /// <summary>
        /// 根据DataSet导出Excel
        /// </summary>
        /// <param name="ds">DataSet</param>
        /// <param name="file">保存地址</param>
        public void GetExcelByDataSet(DataSet ds, string file)
        {
            try
            {
                IWorkbook fileWorkbook = null;
                //IWorkbook fileWorkbook = new HSSFWorkbook();
                int count = ds.Tables.Count;
                if (Path.GetExtension(file) == ".xls")
                {
                    fileWorkbook = new HSSFWorkbook();
                }
                else if (Path.GetExtension(file) == ".xlsx")
                {
                    fileWorkbook = new XSSFWorkbook();
                }
                int index = 0;
                foreach (DataTable dt in ds.Tables)
                {
                    index++;
                    ISheet sheet = fileWorkbook.CreateSheet("Sheet" + index);

                    //表头
                    IRow row = sheet.CreateRow(0);
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        ICell cell = row.CreateCell(i);
                        cell.SetCellValue(dt.Columns[i].ColumnName);
                    }

                    //数据
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        IRow row1 = sheet.CreateRow(i + 1);
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            ICell cell = row1.CreateCell(j);
                            cell.SetCellValue(dt.Rows[i][j].ToString());
                        }
                    }
                }

                //转为字节数组
                MemoryStream stream = new MemoryStream();
                fileWorkbook.Write(stream);
                var buf = stream.ToArray();

                //保存为Excel文件
                using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(buf, 0, buf.Length);
                    fs.Flush();
                }
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
            }
        }

        /// <summary>
        /// 根据单元格将内容返回为对应类型的数据
        /// </summary>
        /// <param name="cell">单元格</param>
        /// <returns>数据</returns>
        private object GetValueTypeForXLS(HSSFCell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:
                    return null;
                case CellType.Boolean: //BOOLEAN:
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:
                    return cell.NumericCellValue;
                case CellType.String: //STRING:
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:
                default:
                    return "=" + cell.CellFormula;
            }
        }
    }
}